<template>
	<view class="pass-rate-chart">
		<qiun-data-charts type="line" :opts="chartOpts" :chartData="chartData"
			canvasId="passRateTrendChart"></qiun-data-charts>
	</view>
</template>

<script>
	export default {
		props: {
			data: {
				type: Array,
				required: true
			}
		},
		data() {
			return {
				chartData: {
					categories: [],
					series: []
				},
				chartOpts: {
					color: ['#3B82F6'],
					padding: [15, 40, 0, 10],
					dataLabel: false,
					dataPointShape: true,
					enableScroll: false,
					legend: {
						show: false
					},
					xAxis: {
						calibration: true,
						disableGrid: true
					},
					yAxis: {
						// 动态设置
					},
					extra: {
						line: {
							type: 'curve',
							width: 2
						},
						markLine: {
							type: 'dash',
							data: []
						}
					}
				}
			};
		},
		// watch: {
		// 	data: {
		// 		handler() {
		// 			this.initChart();
		// 		},
		// 		immediate: true
		// 	}
		// },
		mounted() {
			this.initChart();
		},
		methods: {
			initChart() {
				const categories = [];
				const passRates = [];
				let hasBelow60 = false;

				this.data.forEach((item, i) => {
					categories.push(i + 1);
					passRates.push(item.passRate);
					if (item.passRate < 60) {
						hasBelow60 = true;
					}
				});

				// 判断是否存在小于60的数据
				const yMin = hasBelow60 ? 0 : 60;
				this.chartOpts.yAxis = {
					data: [{
						min: yMin,
						max: 100,
						calibration: true
					}],
					splitNumber: 20,
					labelCount: 20,
					title: '合格率 (%)',
					disabled: false,
				};

				// 辅助线配置：60/70虚线，其余实线
				const passRateLines = [{
						passRate: 60,
						lineColor: '#7a080f',
						lineType: 'dash'
					},
					{
						passRate: 70,
						lineColor: '#d9362c',
						lineType: 'dash'
					},
					{
						passRate: 80,
						lineColor: '#e17908',
						lineType: 'solid'
					},
					{
						passRate: 90,
						lineColor: '#2cb70a',
						lineType: 'solid'
					},
					{
						passRate: 100,
						lineColor: '#0dced2',
						lineType: 'solid'
					}
				];
				this.chartOpts.extra.markLine.data = passRateLines.map(item => ({
					value: item.passRate,
					labelText: item.passRate + '%',
					lineColor: item.lineColor,
					lineType: item.lineType,
					labelAlign: 'right',
					showLabel: true
				}));

				// 设置 chartData
				this.chartData = {
					categories,
					series: [{
						name: '合格率',
						data: passRates
					}]
				};
			}
		}
	};
</script>

<style scoped>
	.pass-rate-chart {
		display: flex;
		flex-direction: column;
		padding: 20rpx;
	}

	qiun-data-charts {
		width: 100%;
		height: 300px;
		margin-bottom: 40rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}
</style>